<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <router-link to="/landCenter/customManage">客户管理</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>{{menuName}}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div style="margin: 24px;">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-tabs
          v-if="!isEditpage"
          type="card"
          v-model="form.isCompany"
          @change="onchangeIsCompany"
          :tabBarStyle="{margin: '0 0 -1px -1px'}"
        >
          <a-tab-pane :key="1" tab="企业"></a-tab-pane>
          <a-tab-pane :key="0" tab="个人"></a-tab-pane>
        </a-tabs>
        <a-card>
          <div class="card-title hasContent">基础信息</div>
          <a-row :gutter="[25]">
            <a-col :span="12">
              <a-form-model-item prop="name" :label="isCompany?'公司名称':'名字'">
                <a-input
                  :disabled="isEditpage && isChosen && form.id != null"
                  v-model="form.name"
                  :max-length="50"
                  @blur="onBlurCheck"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="isCompany">
              <a-form-model-item prop="identityCard" label="统一信用代码">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.identityCard"
                  :max-length="30"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="!isCompany">
              <a-form-model-item prop="personIdentityCard" label="身份证号">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.identityCard"
                  :max-length="18"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="isCompany">
              <a-form-model-item prop="linkMan1" label="联系人">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.linkMan1"
                  :max-length="10"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="linkManPhone1" label="联系电话">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.linkManPhone1"
                  :max-length="20"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="isCompany">
              <a-form-model-item prop="linkMan2" label="联系人2">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.linkMan2"
                  :max-length="10"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="isCompany">
              <a-form-model-item prop="linkManPhone2" label="联系电话2">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.linkManPhone2"
                  :max-length="20"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="isCompany">
              <a-form-model-item prop="address" label="公司地址">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.address"
                  :max-length="100"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="isCompany">
              <a-form-model-item prop="phone" label="公司电话">
                <a-input
                  :disabled="isChosen && form.id != null"
                  v-model="form.phone"
                  :max-length="20"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="userId" label="所属销售">
                <a-select v-model="form.userId">
                  <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" style="padding: 0">
              <a-col :span="12" v-if="isCompany" class="busenPic">
                <a-form-model-item prop="businessLicensePic" label="营业执照">
                  <ud-upload
                    v-show="!isChosen"
                    :length="1"
                    @uploadFile="businessLicenseUpload"
                    :optList="businessLicensePicStr"
                  ></ud-upload>
                  <img
                    class="previewImageClass"
                    v-show="isChosen && form.id != null"
                    :src="form.businessLicensePic"
                    @click="previewImageModal(form.businessLicensePic)"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12" v-if="isCompany" class="busenPic">
                <a-form-model-item prop="accountOpenLicensePic" label="开户许可证">
                  <ud-upload
                    v-show="!isChosen"
                    :length="1"
                    @uploadFile="accountOpenLicenseUpload"
                    :optList="accountOpenLicensePicStr"
                  ></ud-upload>
                  <img
                    class="previewImageClass"
                    v-show="isChosen && form.id != null"
                    :src="form.accountOpenLicensePic"
                    @click="previewImageModal(form.accountOpenLicensePic)"
                  />
                </a-form-model-item>
              </a-col>
            </a-col>
          </a-row>
        </a-card>

        <a-card>
          <div class="card-title hasContent">开票及结算信息</div>
          <a-row :gutter="[25]">
            <a-col :span="12">
              <a-form-model-item prop="settlementType" label="结算类型">
                <a-select
                  v-model="form.custInfoSettlement.settlementType"
                  @change="settlementTypeChange"
                  class="selectWidth"
                >
                  <a-select-option value>请选择</a-select-option>
                  <a-select-option v-for="v in settlementTypeList" :key="v.key">{{v.value}}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item prop="paymentDays" label="账期">
                <a-select
                  v-model="form.custInfoSettlement.paymentDays"
                  class="selectWidth"
                  :options="OptionPaymentDays"
                ></a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="22" :offset="1">
              <a-form-model-item prop="custInfoBankCardList">
                <h3 style="fontWeight:bold; display:inline-block;marginRight:24px">银行卡信息</h3>
                <a-button
                  v-if="form.custInfoBankCardList.length < 5"
                  type="primary"
                  @click="addCard"
                >添加银行卡</a-button>
              </a-form-model-item>
              <div id="banks">
                <bank-card-list
                  :list="form.custInfoBankCardList"
                  @handle-delete="handleDelete"
                  @handle-edit="handleEdit"
                />
              </div>
            </a-col>
          </a-row>
        </a-card>

        <a-card>
          <div class="card-title hasContent">合同信息</div>
          <a-button type="primary" class="cardEdit" @click="uploadAgreement">
            <a-icon type="upload" />上传合同
          </a-button>
          <a-row>
            <a-col :span="22" :offset="1">
              <a-list>
                <a-list-item v-for="(ag, index) in this.form.custInfoContractList" :key="index">
                  <a-icon type="link" :style="{color: getColor(ag.beginTime, ag.endTime)}" />
                  合同有效期：{{ag.beginTime}} ~ {{ag.endTime}}
                  <a @click="checkAgreement(index)">查看</a>
                </a-list-item>
              </a-list>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </div>
    <div class="creat_button">
      <a-button
        type="primary"
        @click="save"
        :saveLoading="saveLoading"
        style="margin-left: 20px; float: right;  margin-top:12px;"
      >提交</a-button>
      <a-button @click="cancelCreate" style="float: right;  margin-top:12px;">取消</a-button>
    </div>

    <bank-card-modal
      :visible="bankCardVisible"
      :bank="custInfoBankCardInfo"
      :index="cardIndex"
      @set-bankcard-visible="setBankcardVisible"
      @handle-bank-card="handleBankCard"
    />
    <agreement-modal
      :visible="agreementVisible"
      @set-agreement-visible="setAgreementVisible"
      @handle-agreement="handleAgreement"
    />
    <agreement-view-modal
      :visible="agreementViewVisible"
      :agreement="custInfoContract"
      @set-agview-visible="setAgreementViewVisible"
    />
    <preview-img-modal v-if="previewImage" :src="previewImage" @clear-src="clearSrc" />
  </div>
</template>

<script>
import { mixin } from '@/common/settlement2'
import { getExistCustomerByName, addCustomer, editCustomer, getCustomerById, querySellerDown } from '@/api'
import upload from '@/components/UpLoad'
import bankCardList from '@/page/landCenter/bankCardList'
import bankCardModal from '@/page/landCenter/bankCardOperateModal'
import agreementModal from '@/page/landCenter/agreementUploadModal'
import agreementViewModal from '@/page/landCenter/agreementViewModal'

const fomrMessage = `必填项不能为空`

const CUSTOMER = 'CUSTOMER'
const OptionPaymentDays = [
  {
    key: 30, title: '30天'
  }, {
    key: 60, title: '60天'
  }, {
    key: 90, title: '90天'
  }, {
    key: 120, title: '120天'
  }, {
    key: 150, title: '150天'
  }, {
    key: 180, title: '180天'
  }
]

const defaultForm = (isCompany = 1) => ({
  custType: CUSTOMER,
  belongCompany: 'JIA_TE',
  isReceivable: 0,
  isPayable: 0,
  status: 1,
  userId: '',
  isCompany,
  name: '', // 公司名称
  identityCard: '', // 统一信用代码
  linkMan1: '', // 联系人1
  linkManPhone1: '', // 联系电话1
  linkMan2: '', // 联系人2
  linkManPhone2: '', // 联系电话2
  address: '', // 地址
  businessLicensePic: '', // 营业执照图
  accountOpenLicensePic: '', // 开户许可证
  custInfoSettlement: {
    custType: CUSTOMER, // 客户类型
    settlementType: 1, // 结算方式：1票结，2月结
    paymentDays: '' // 账期
  },
  custInfoBankCardList: [],
  custInfoContractList: []
})

export default {
  mixins: [mixin],
  data () {
    // 结算类型
    let settlementTypeValidator = (rule, value, callback) => {
      if (!this.form.custInfoSettlement.settlementType) {
        callback(new Error(fomrMessage))
      } else {
        callback()
      }
    }

    // 验证银行卡
    let custInfoBankCardsValidator = (rule, value, callback) => {
      if (this.form.custInfoBankCardList.length === 0) {
        callback(new Error('至少添加一张银行卡'))
      } else {
        callback()
      }
    }

    return {
      sellers: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      OptionPaymentDays: null,
      formId: null, // 名称选择的对象
      nameLikeData: [],
      previewImage: null,
      form: defaultForm(),
      custInfoBankCardInfo: {
        custType: CUSTOMER, // 客户类型
        accountName: '', // 开户名称
        accountNumber: '', // 银行卡账号
        openingBank: '', // 银行卡开户行
        picture: '' // 银行卡正面照
      },
      custInfoContract: {
        custType: CUSTOMER, // 客户类型
        name: '', // 合同名称
        beginTime: '', // 合同有效期
        endTime: '', // 合同有效期
        pictures: '' // 上传合同
      },
      isEditpage: false,
      editId: null,
      rules: {
        name: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        identityCard: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        linkMan1: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        linkManPhone1: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        address: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        businessLicensePic: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        // accountOpenLicensePic: [{required: true, message: fomrMessage, trigger: 'blur'}],
        userId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        settlementType: [{ required: true, validator: settlementTypeValidator, trigger: ['blur', 'change'] }],
        custInfoBankCardList: [{ validator: custInfoBankCardsValidator }]
      },
      saveLoading: false,
      // 编辑银行卡
      bankCardVisible: false,
      cardIndex: null, // 记录编辑的第几个
      // 合同
      agreementVisible: false,
      agreementViewVisible: false
    }
  },
  components: {
    'ud-upload': upload,
    [bankCardList.name]: bankCardList,
    [bankCardModal.name]: bankCardModal,
    [agreementModal.name]: agreementModal,
    [agreementViewModal.name]: agreementViewModal
  },
  computed: {
    menuName () {
      return this.$route.query.id ? '编辑客户' : '创建客户'
    },
    isCompany () {
      return this.form.isCompany === 1
    },
    businessLicensePicStr () {
      return this.form.businessLicensePic ? [this.form.businessLicensePic] : []
    }, // 营业执照图
    accountOpenLicensePicStr () {
      return this.form.accountOpenLicensePic ? [this.form.accountOpenLicensePic] : []
    },
    isChosen () {
      return this.form.isPayable !== 0 || this.form.isReceivable !== 0
    }
  },
  methods: {
    getColor (beginTime, endTime) {
      const isOver = new Date(`${endTime} 23:59:59`).getTime() < new Date().getTime() || new Date(`${beginTime}`).getTime() > new Date().getTime()
      return isOver ? 'grey' : '#1890ff'
    },
    onchangeIsCompany (activeKey) {
      this.form.isCompany = activeKey
      if (!this.isEditpage) {
        this.form = defaultForm(activeKey)
        this.form.userId = this.sellers[0].uiId || ''
      }
    },
    businessLicenseUpload (val) {
      this.form.businessLicensePic = val
      this.$refs.ruleForm.validateField('businessLicensePic', msg => { })
    },
    accountOpenLicenseUpload (val) {
      this.form.accountOpenLicensePic = val
      this.$refs.ruleForm.validateField('accountOpenLicensePic', msg => { })
    },
    settlementTypeChange () {
      if (this.form.custInfoSettlement.settlementType === 2) {
        this.OptionPaymentDays = OptionPaymentDays
        this.form.custInfoSettlement.paymentDays = OptionPaymentDays[0].key
      } else {
        this.OptionPaymentDays = null
        this.form.custInfoSettlement.paymentDays = null
      }
    },
    addCard () {
      this.cardIndex = null
      this.bankCardVisible = true
    },
    setBankcardVisible (visible) {
      this.bankCardVisible = visible
    },
    handleDelete (index) {
      this.form.custInfoBankCardList.splice(index, 1)
    },
    handleEdit (index) {
      this.cardIndex = index
      Object.assign(this.custInfoBankCardInfo, this.form.custInfoBankCardList[index])
      this.bankCardVisible = true
    },
    handleBankCard (index, card) {
      if (index === 0 || index) this.form.custInfoBankCardList[index] = { ...card, custType: CUSTOMER }
      else this.form.custInfoBankCardList.push({ ...card, custType: CUSTOMER })
      this.form.custInfoBankCardList = [...this.form.custInfoBankCardList]
      this.bankCardVisible = false
      this.$refs.ruleForm.validateField('custInfoBankCardList', msg => { })
    },
    uploadAgreement () {
      this.agreementVisible = true
    },
    setAgreementVisible (visible) {
      this.agreementVisible = visible
    },
    handleAgreement (agreement) {
      this.form.custInfoContractList.push({ ...agreement, custType: CUSTOMER })
      this.agreementVisible = false
    },
    checkAgreement (index) {
      this.agreementViewVisible = true
      this.custInfoContract = Object.assign({}, this.form.custInfoContractList[index])
    },
    setAgreementViewVisible (visible) {
      this.agreementViewVisible = visible
    },
    onBlurCheck (e) {
      const value = e.target.value
      // const isCompany = this.form.isCompany
      if (value) {
        const data = { custName: value, belongCompany: 'JIA_TE', searchType: 3, custId: this.editId }
        getExistCustomerByName(data).then(rsp => {
          if (rsp.data) {
            Object.assign(this.form, rsp.data, { custType: CUSTOMER })
            this.$refs.ruleForm.validateField('businessLicensePic', msg => { })
            this.$refs.ruleForm.validateField('accountOpenLicensePic', msg => { })
          } else {
            this.form.isPayable = 0
            this.form.isReceivable = 0
          }
          // this.form.userId = this.sellers[0].uiId || ''
        }).catch(() => {
          this.form.name = ''
        })
      } else {
        this.form.isPayable = 0
        this.form.isReceivable = 0
      }
    },
    cancelCreate () {
      let _t = this
      this.$confirm({
        title: '还有未保存的信息，退出后编辑的数据将消失，确定退出？',
        onOk () {
          _t.$router.push('/landCenter/customManage')
        }
      })
    },
    save () {
      this.saveLoading = true
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.form.isCompany === 0) { // 个人，赋值
            this.form.linkMan1 = this.form.name
            this.form.phone = this.form.linkManPhone1
          }
          if (this.formId || this.form.id) {
            // 编辑
            let id = this.formId || this.form.id
            editCustomer({ ...this.form, id }).then(rsp => {
              this.$message.success('提交成功')
              this.$router.push('/landCenter/customManage')
            }).catch(() => {
              this.saveLoading = false
            })
          } else {
            // 新增
            addCustomer(this.form).then(rsp => {
              this.$message.success('提交成功')
              this.$router.push('/landCenter/customManage')
            }).catch(() => {
              this.saveLoading = false
            })
          }
        } else {
          this.saveLoading = false
        }
      })
    },
    previewImageModal (src) {
      this.previewImage = src
    },
    clearSrc () {
      this.previewImage = null
    }
  },
  mounted () {
    this.$nextTick(() => {
      const id = this.$route.query.id
      if (id) {
        this.isEditpage = true
        this.editId = id
        getCustomerById({ id, custType: CUSTOMER }).then(rsp => {
          Object.assign(this.form, rsp.data, { custType: CUSTOMER })

          if (this.form.custInfoSettlement.settlementType === 2) {
            this.OptionPaymentDays = OptionPaymentDays
          }
        })
      }

      querySellerDown({
        type: 1,
        dataRole: 'LAND_SELL',
        status: 1
      }).then(rsp => {
        this.sellers = rsp.data.map((v, i) => {
          if (!v.uiId) {
            v.name = '请选择'
            v.uiId = ''
          }
          return v
        })
        if (!id && id !== 0) {
          this.form.userId = this.sellers[0].uiId || ''
        }
      })
    })
  }
}
</script>

<style lang="less" scoped>
.ant-card {
  position: relative;
  margin-bottom: 24px;
  border: none;
  .cardEdit {
    position: absolute;
    right: 24px;
    top: 24px;
    z-index: 2;
  }
  .card-title {
    position: relative;
    padding-left: 16px;
    font-size: 18px;
    line-height: 1;
    color: #000;
    &:before {
      content: '';
      width: 5px;
      height: 18px;
      background: #1890ff;
      border-radius: 4px;
      position: absolute;
      left: 0;
      top: -1px;
    }
  }
  .hasContent {
    margin-bottom: 20px;
  }
}
</style>
